package com.coincalf.wallet.web;

import com.coincalf.framework.enums.ResultCode;
import com.coincalf.framework.http.Response;
import com.coincalf.framework.utils.TokenUtil;
import com.coincalf.user.dto.UserDTO;
import com.coincalf.user.feign.UserServiceClient;
import com.coincalf.wallet.entity.UserInfo;
import com.coincalf.wallet.service.UserAddressService;
import com.coincalf.wallet.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 * 用户的地址池 前端控制器
 * </p>
 *
 * @author crow
 * @since 2018-05-16
 */
@Slf4j
@RestController
@RequestMapping("/address")
public class UserAddressController {

    @Autowired
    private UserAddressService userAddressService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private UserServiceClient userServiceClient;

    /**
     * 获取钱包充值地址
     *
     * @param coinId     币种ID
     * @param mainCoinId 主链币种ID
     * @return
     */
    @GetMapping
    public Response getAddress(HttpServletRequest request,
                               @RequestParam("userId") Long userId,
                               @RequestParam("coinId") Long coinId,
                               @RequestParam(value = "mainCoinId", required = false) Long mainCoinId) {
        String token = request.getHeader("TOKEN");
        if (!StringUtils.isEmpty(token)) {
            Map<String, Object> map = TokenUtil.parserImToken(token);
            String mobile = map.get("username").toString();
            UserInfo userInfo = userInfoService.selectByPhone(mobile);
            if (userInfo != null) {
                userId = userInfo.getId();
            }
        } else {
            //判断userId是否合法
            UserDTO userDTO = userServiceClient.selectById(userId);
            if (userDTO == null) {
                return Response.err(ResultCode.USER_NOT_EXIST);
            }
        }
        Map<String, String> address = userAddressService.getAddress(userId, coinId, mainCoinId);
        return Response.ok(address);
    }

}

